import axios from "axios";
import { Notification, Message } from "element-ui"
import { removeToken, getToken } from '@/utils/auth';

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_URL,
    timeout: 3*1000,
});

let errorcountlist = [];
let timer = null;
// 请求拦截
service.interceptors.request.use(config=>{
    config.data = JSON.stringify(config.data); //数据转化,也可以使用qs转换
    config.headers = {
      'Content-Type':'application/json;charset=utf-8', //配置请求头
   
    }
    return config;
}, error=> {
    return Promise.reject(error);
});


// 响应拦截
service.interceptors.response.use(
    (res) => {
            // 未设置状态码则默认成功状态
        const code = res.data.code || 200
        const msg = res.data.message;
        if (code === 500) {   
            Message({
                message: msg,
                type: "error",
                offset: window.screen.height / 3,
            })
            return Promise.reject(msg)
        } else if (code !== 200) {
            Message({
                message: msg,
                type: "error",
                offset: window.screen.height / 3,
            })
            // Notification.error({
            //     title: msg,
            // })
            return Promise.reject("error")
        } else {
            return res.data;
           
        }
    },
    (error) => {
        let code = (error.response && error.response.status) || ""
            console.log(code, 'code')
        if (code === 401) {
            Message({
                message: (error.response && error.response.data) ? error.response.data.message : '发生错误:' + code + ',请重试',
                type: 'error',
                duration: 3 * 1000,
                offset: window.screen.height / 3,
            })
           
        } else if(code == 503){
            Message({
                message: '服务忙，请稍后重试',
                type: "error",
                offset: window.screen.height / 3,
            })
        }else{
            if (!errorcountlist.includes(code) && code) {
                Message({
                    message: (error.response && error.response.data) ? error.response.data.message : '发生错误:' + code + ',请重试',
                    type: 'error',
                    duration: 3 * 1000,
                    offset: window.screen.height / 3
                })
                errorcountlist.push(code)
                clearTimeout(timer)
            }
            timer = setTimeout(() => {
                errorcountlist = []
            }, 2500)
            return Promise.reject(error)
        }
    }
)



export default service;